package com.softstao.guoyu.ui.activity.me;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.agent.SubAuditInfo;
import com.softstao.guoyu.model.me.AuditDetail;
import com.softstao.guoyu.model.me.AuditHistory;
import com.softstao.guoyu.model.me.Level;
import com.softstao.guoyu.model.me.User;
import com.softstao.guoyu.mvp.interactor.me.AuditInteractor;
import com.softstao.guoyu.mvp.presenter.me.AuditPresenter;
import com.softstao.guoyu.mvp.viewer.me.AuditDetailViewer;
import com.softstao.guoyu.mvp.viewer.me.CancelApplyViewer;
import com.softstao.guoyu.ui.activity.agent.AuditStatusActivity;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.softstaolibrary.library.activity.PhotoActivity;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.MarginDecoration2;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/24.
 */

public class AuditDetailActivity extends BaseActivity implements AuditDetailViewer,CancelApplyViewer {

    @AIPresenter(presenter = AuditPresenter.class, interactor = AuditInteractor.class)
    AuditPresenter presenter;

    @BindView(R.id.submit_btn)
    TextView submitBtn;
    @BindView(R.id.edit_btn_view)
    LinearLayout editBtnView;
    @BindView(R.id.user_id)
    TextView userId;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.mobile)
    TextView mobile;
    @BindView(R.id.wechat)
    TextView wechat;
    @BindView(R.id.current_level)
    TextView currentLevel;
    @BindView(R.id.parent_name)
    TextView parentName;
    @BindView(R.id.apply_time)
    TextView applyTime;
    @BindView(R.id.apply_reason)
    EditText applyReason;
    @BindView(R.id.bond)
    TextView bond;
    @BindView(R.id.level_name)
    TextView levelName;
    @BindView(R.id.memo)
    TextView memo;
    @BindView(R.id.audit_history_view)
    RecyclerView auditHistoryView;
    @BindView(R.id.history_view)
    LinearLayout historyView;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.pay_img)
    LinearLayout payImg;
    @BindView(R.id.confirm_btn)
    TextView confirmBtn;
    @BindView(R.id.reject_btn)
    TextView rejectBtn;
    private User user;
    private AuditDetail auditDetail;
    private SubAuditInfo subAuditInfo;
    private String type;
    private String level_name = "";
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private int proccess_id;
    private int status;
    private int flag;
    private Level level;
    private List<AuditHistory> auditList = new ArrayList<>();
    private RecycleViewBaseAdapter<AuditHistory> adapter;
    private static List<Level> levelList = new ArrayList<>();
    private final static int CONFIRM = 1;
    private final static int REJECT = 2;
    private final static int AGAIN = 3;

    @Override
    public int _ContentView() {
        return R.layout.activity_audit_add;
    }

    @Override
    public void initView() {
        type = getIntent().getStringExtra("type");
        payImg.setVisibility(View.GONE);
        applyReason.setEnabled(false);
        historyView.setVisibility(View.VISIBLE);
        user = UserManager.getInstance().getUser();
        switch (type) {
            case "user":
                flag = getIntent().getIntExtra("flag",0);
                bottom.setVisibility(View.GONE);
                userId.setText(SharePreferenceManager.getInstance().getAgentId()+"");
                name.setText(user.getName());
                mobile.setText(user.getMobile());
                wechat.setText(user.getWechat());
                switch (User.Type.fromInteger(user.getLevel())) {
                    case ANGEL:
                        level_name = "天使";
                        break;
                    case CROWN:
                        level_name = "皇冠";
                        break;
                    case ONE_LEVEL:
                        level_name = "一级";
                        break;
                    case CITY_LEVEL:
                        level_name = "市级";
                        break;
                    case PROVINCE:
                        level_name = "省代";
                        break;
                    case HEADQUARTER:
                        level_name = "总部";
                        break;
                    case UNAGENT:
                        level_name = "未授权";
                        break;
                }
                currentLevel.setText(level_name);
                parentName.setText(user.getParentName());
                if (flag==1){
                    bottom.setVisibility(View.VISIBLE);
                    submitBtn.setVisibility(View.GONE);
                    editBtnView.setVisibility(View.VISIBLE);
                    confirmBtn.setText("重新编辑提交");
                    rejectBtn.setText("取消升级");
                }
                break;
            case "agent":
                status = getIntent().getIntExtra("status", 0);
                submitBtn.setVisibility(View.GONE);
                bottom.setVisibility(View.VISIBLE);
                switch (status) {
                    case 1:
                        editBtnView.setVisibility(View.VISIBLE);
                        confirmBtn.setText("确认通过");
                        rejectBtn.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        bottom.setVisibility(View.GONE);
                        break;
                    case 3:
                        bottom.setVisibility(View.GONE);
                        break;
                }
                break;
        }

        AuditHistoryActivity.setLevel(levelList);
        proccess_id = getIntent().getIntExtra("id", 0);
        initTitle("授权申请详情");

        adapter = new RecycleViewBaseAdapter<AuditHistory>(auditList, R.layout.layout_audit_history_item) {
            @Override
            public void convert(RecycleViewHolder holder, AuditHistory auditHistory) {
                RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                holder.itemView.setLayoutParams(layoutParams);
                String name = null, status = null;
                switch (auditHistory.getAuditAgentLevel()) {
                    case 1:
                        name = "天使";
                        break;
                    case 2:
                        name = "皇冠";
                        break;
                    case 3:
                        name = "一级";
                        break;
                    case 4:
                        name = "市级";
                        break;
                    case 5:
                        name = "省级";
                        break;
                    case 6:
                        name = "总部";
                        break;
                    case 7:
                        name = "未授权";
                        break;
                }
                switch (auditHistory.getState()) {
                    case -1:
                        status = "已驳回";
                        break;
                    case 0:
                        status = "";
                        break;
                    case 1:
                        status = "已提交";
                        break;
                    case 2:
                        status = "已通过";
                        break;
                }
                String date = auditHistory.getUpdateDate() == 0 ? "——" : format.format(new Date(auditHistory.getUpdateDate()));
                holder.setText(R.id.agent_level, name)
                        .setText(R.id.status, status)
                        .setText(R.id.agent_name, auditHistory.getAuditAgentName())
                        .setText(R.id.time, date);
                if (auditHistory.getReason() != null && !auditHistory.getReason().equals("")) {
                    holder.getView(R.id.reason).setVisibility(View.VISIBLE);
                    holder.setText(R.id.reason, auditHistory.getReason());
                } else {
                    holder.getView(R.id.reason).setVisibility(View.GONE);
                }
                if (auditHistory.getImg() != null && !auditHistory.getImg().equals("")) {
                    holder.getView(R.id.img_view).setVisibility(View.VISIBLE);
                    Glide.with(context).load(auditHistory.getImg()).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v -> startActivity(new Intent(context, PhotoActivity.class).putExtra("url", auditHistory.getImg())));
                } else {
                    holder.getView(R.id.img_view).setVisibility(View.GONE);
                }
            }
        };
        auditHistoryView.setAdapter(adapter);
        auditHistoryView.setLayoutManager(new FullyLinearLayoutManager(this));
        auditHistoryView.addItemDecoration(new MarginDecoration2(this));
    }

    private void initData() {
        userId.setText(String.valueOf(subAuditInfo.getSubAgentId()));
        name.setText(subAuditInfo.getSubAgentname());
        mobile.setText(subAuditInfo.getSubAgentMobile());
        wechat.setText(subAuditInfo.getSubAgentWechat());
        switch (User.Type.fromInteger(subAuditInfo.getSubAgentLevel())) {
            case ANGEL:
                level_name = "天使";
                break;
            case CROWN:
                level_name = "皇冠";
                break;
            case ONE_LEVEL:
                level_name = "一级";
                break;
            case CITY_LEVEL:
                level_name = "市级";
                break;
            case PROVINCE:
                level_name = "省代";
                break;
            case HEADQUARTER:
                level_name = "总部";
                break;
            case UNAGENT:
                level_name = "未授权";
                break;
        }
        currentLevel.setText(level_name);
        parentName.setText(subAuditInfo.getSubAgentParent());
        bond.setText(LZUtils.priceFormat(subAuditInfo.getSubAgentBond()) + "元");
    }

    @OnClick({R.id.confirm_btn, R.id.reject_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.confirm_btn:
                switch (type){
                    case "user":
                        if (flag==1){
                            Intent intent = new Intent(context,AuditAddActivity.class);
                            intent.putExtra("level",level);
                            intent.putExtra("detail",auditDetail);
                            intent.putExtra("id",proccess_id);
                            startActivityForResult(intent,AGAIN);
                        }
                        break;
                    case "agent":
                        Intent confirmIntent = new Intent(context, AuditStatusActivity.class);
                        confirmIntent.putExtra("id", proccess_id);
                        confirmIntent.putExtra("flag", 0);
                        confirmIntent.putExtra("level",level);
                        startActivityForResult(confirmIntent,CONFIRM);
                        break;
                }
                break;
            case R.id.reject_btn:
                switch (type) {
                    case "user":
                        if (flag == 1) {
                            new AlertDialog.Builder(context)
                                    .setMessage("确定取消升级？")
                                    .setPositiveButton("确定",(dialog, which) -> {
                                        cancelApply();
                                        dialog.dismiss();
                                    })
                                    .setNegativeButton("取消",(dialog, which) -> dialog.dismiss())
                                    .create().show();
                        }
                        break;
                    case "agent":
                        Intent intent = new Intent(context, AuditStatusActivity.class);
                        intent.putExtra("id", proccess_id);
                        intent.putExtra("flag", 2);
                        startActivityForResult(intent,REJECT);
                        break;
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getAuditDetail();
    }

    @Override
    public void getAuditDetail() {
        loading.setVisibility(View.VISIBLE);
        presenter.getAuditDetail(SharePreferenceManager.getInstance().getAgentId(), proccess_id);
    }

    @Override
    public void getResult(AuditDetail auditDetail) {
        if (auditDetail != null) {
            this.auditDetail = auditDetail;
            if (auditDetail.getAuditList() != null) {
                auditList.clear();
                auditList.addAll(auditDetail.getAuditList());
                adapter.notifyDataSetChanged();
            }
            applyReason.setText(auditDetail.getApplyReason());
            String time = auditDetail.getApplyTime() == 0 ? "——" : format.format(new Date(auditDetail.getApplyTime()));
            applyTime.setText(time);
            switch (User.Type.fromInteger(auditDetail.getApplyLevel())) {
                case ANGEL:
                    level = levelList.get(4);
                    break;
                case CROWN:
                    level = levelList.get(3);
                    break;
                case ONE_LEVEL:
                    level = levelList.get(2);
                    break;
                case CITY_LEVEL:
                    level = levelList.get(1);
                    break;
                case PROVINCE:
                    level = levelList.get(0);
                    break;
            }
            level_name = level.getName();
            initTitle(level_name.substring(0, 2) + "授权申请详情");
            levelName.setText(level_name);
            memo.setText(level.getMemo());
            if (auditDetail.getSubAuditInfo() != null) {
                this.subAuditInfo = auditDetail.getSubAuditInfo();
                initData();
            }
        }
        loading.setVisibility(View.GONE);
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            switch (requestCode) {
                case CONFIRM:
                    bottom.setVisibility(View.GONE);
                    break;
                case REJECT:
                    bottom.setVisibility(View.GONE);
                    break;
                case AGAIN:
                    bottom.setVisibility(View.GONE);
                    break;
            }
        }
    }

    @Override
    public void cancelApply() {
        loading.setVisibility(View.VISIBLE);
        presenter.cancel(SharePreferenceManager.getInstance().getAgentId(),proccess_id);
    }

    @Override
    public void cancelResult(Object result) {
        loading.setVisibility(View.GONE);
        LZToast.getInstance(context).showToast("取消成功");
        finish();
    }
}
